<?php
namespace App\Libs\wrapper;
use Illuminate\Support\Facades\DB;
class Role extends Comm{
//////////////////////////////////////////////// 角色
////////////////////// 角色列表
	/**
	 * @desc 角色列表--数据
	 * @param name 角色名称
	 * @param page 页码
	 * @param page_count 每页条数
	 */
	public function role_list($data){
        $where = "1=1";
        //name 角色名称
        $userId = $data['user_info']['Id'];
		$limit = "";
		if((!empty($data['page'])) and (!empty($data['page_count']))){
            $data['page_count'] = 50;
			$limit = " limit ".($data['page']-1)*$data['page_count'].",{$data['page_count']}";
		}


        if(isset($data['id'])){
            //var_dump($data['id']);die;
            $where .= " and `pid` = {$data['id']}";
        }else{
            if($data['power']['powers_role_update']==false){
                $sqlRole = "select *
                    from xt_role_user_join
                    where user_id = {$userId}";
                $listRole = json_decode(json_encode(db::select($sqlRole)),true);
//                var_dump($listRole);die;
                foreach ($listRole as $k =>$v){
                    $sql = "select *
                    from xt_role
                    where `id` in ({$v['role_id']})";
                    $role = json_decode(json_encode(db::select($sql)),true);
                    foreach ($role as $ke =>$va){
                        $rolePid[] = $va['pid'];
                    }
                    //$roleId[] = $v['role_id'];

                }//die;
                $roleId = implode(',',$rolePid);
                //var_dump($roleId);die;
                $where .= " and `id` in ({$roleId}) and `pid`=0";
                $return['add_power'] = 1;
                //var_dump($roleId);
            }else{
                $where .= " and `pid` = 0";
            }

            //var_dump($where);die;
        }
        $sql = "select *
                    from xt_role
                    where {$where} {$limit}";
        $list = json_decode(json_encode(db::select($sql)),true);
        // var_dump($sql);die;
        //var_dump($list);die;
        //// 总条数
		if(isset($data['page']) and isset($data['page_count'])){
			$total = db::select("SELECT FOUND_ROWS() as total");
			$return['total'] = $total[0]->total;
		}
        $return['list'] = $list;
        return $return;
    }
	
	/**
	 * 新增角色
	 * @param name 角色名称
	 * @param desc 角色描述
	 */
	public function role_add($data){
		//检测角色唯一性
		$sql = "select `Id`
					from xt_role
					where `name`='{$data['name']}'";
		$find = db::select($sql);
		if(!empty($find)){
			return '该角色已存在';
		}
		
		//新增角色
		$field_arr = array('name', 'desc');
		$field = "";
		$insert = "";
		foreach ($data as $k=>$v){
			if(in_array($k, $field_arr)){
				$field .= ",`{$k}`";
				$insert .= ",'{$v}'";
			}
		}
		$field = substr($field, 1);
		$insert = substr($insert, 1);
		//var_dump($data);die;
		if(isset($data['id'])){
		    $field.=",`pid`";
		    $insert.=",{$data['id']}";
        }
		//var_dump($field);die;
		if(isset($data['power'])){
            $field.=",`power`";
		    $insert .= ",{$data['power']}";
        }
		//var_dump($insert);die;
		//var_dump($insert);die;
		$sql = "insert ignore into xt_role({$field}) values ({$insert})";
		$add = db::insert($sql);
		if($add){
			return 1;
		}else{
			return '新增失败';
		}
    }
	
	/**
	 * 角色信息
	 * @param Id 角色id
	 */
	public function role_info($data){
		$where = "1=1";
		//Id 角色id
		if(!empty($data['Id'])){
			$where .= " and `Id`={$data['Id']}";
		}
		
		$sql = "select *
					from xt_role
					where {$where}";
		$find = json_decode(json_encode(db::select($sql)),true);
		return $find;
	}
	
	/**
	 * 编辑角色
	 * @param Id 角色id
	 * @param name 角色名称
	 * @param desc 角色描述
	 */
	public function role_update($data){
		$set = "";
		//name 角色名称
		if(!empty($data['name'])){
			//检测角色唯一性
			$sql = "select `Id` from xt_role where `name`='{$data['name']}' and `Id`!={$data['Id']}";
			$find = db::select($sql);
			if(!empty($find)){
				return '该角色已存在';
			}
			$set .= ",`name`='{$data['name']}'";
		}
		//desc 角色描述
		if(!empty($data['desc'])){
			$set .= ",`desc`='{$data['desc']}'";
		}
        //岗位职责
        if(!empty($data['text'])){
            $set .= ",`text`='{$data['text']}'";
        }
        if(!empty($data['power'])){
            $set .= ",`desc`='{$data['desc']}'";
        }
		
		if(empty($set)){
			return '更新数据为空';
		}else{
			$set = substr($set, 1);
		}
		
		$sql = "update xt_role
					set {$set}
					where `Id` = {$data['Id']}";
		$update = db::update($sql);
		if($update !== false){
			return 1;
		}else{
			return '编辑失败';
		}
    }
	
	/**
	 * 删除角色
	 * @param Id 角色id
	 */
	public function role_del($Id){
		//删除角色表、用户与角色关系表、角色与权限关系表
        $sql = "select * from xt_role where pid={$Id}";
        $res = json_decode(json_encode(db::select($sql)),true);

        if(!empty($res)){
            //echo "11";
            //var_dump($res);die;
            return "该分类下还有内容，无法删除";
        }//die;
		$sql = "delete r, ru, rp
					from xt_role r
					left join xt_role_user_join ru on ru.role_id = r.Id
					left join xt_powers_role_join rp on rp.role_id = r.Id
					where r.`Id` = {$Id}";
		$del = db::delete($sql);
		if($del){
			return 1;
		}else{
			return '删除失败';
		}
    }


////////////////////// 角色权限
	/**
	 * 编辑角色权限
	 * @param role_id 角色id
	 * @apram power_ids 权限id 例如：1,2,3,
	 */
	public function powers_role_update($data){
		db::beginTransaction();	//开启事务
		
		//删除角色所有权限
		$sql = "delete
					from xt_powers_role_join
					where role_id = {$data['role_id']}";
		$del = db::delete($sql);
        $sql = "select *
					from xt_role
					where Id = {$data['role_id']}";
        $roleData = json_decode(json_encode(db::select($sql)),true);

//echo "<pre>";

		$insert = "";
		$ids = explode(',', $data['power_ids']);

		foreach ($ids as $v){
			$insert .= ",({$data['role_id']}, {$v})";
		}
		$insert = substr($insert, 1);
		//var_dump($ids);die;
		$sql = "insert into xt_powers_role_join(`role_id`, `power_id`) values {$insert}";
		$add = db::insert($sql);
		if($add){
            if($roleData[0]['power']==1){
                $sql = "select *
					from xt_role
					where pid = {$roleData[0]['pid']} and power!=1";
                $userData = json_decode(json_encode(db::select($sql)),true);
                foreach($userData as $k1=>$v1){
                    $sql = "select *
					from xt_powers_role_join
					where role_id = {$v1['Id']}";
                    $userPower = json_decode(json_encode(db::select($sql)),true);
                    foreach($userPower as $k2=>$v2){
                        //var_dump($v2);die;
                        $roleId = $v2['role_id'];
                        $upId = $v2['power_id'];
                        if(!in_array($upId,$ids)){
                            $sql = "delete
					                from xt_powers_role_join
					                where role_id = {$roleId} and power_id={$upId}";
                            $del = db::delete($sql);
                        }
                        //var_dump($upId );
                    }

                }
                //die;
            }
			db::commit();	//事物确认

			return 1;
		}else{
			db::rollback();	//事务回滚
			return '保存成功';
		}
	}


















}//结束符